package com.qilin.hscs.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 胡晓军 on 2017/10/22.
 */
public class IpAddrUtil {
    private static final Logger logger= LogManager.getLogger(IpAddrUtil.class.getName());
    static final String host = "http://saip.market.alicloudapi.com";
    static final String path = "/ip";
    static final String method = "GET";
    static final String appcode = "e04deec181e94c079ff8bb482f02a6c6";
    public static String getIpAddr(String ip) throws Exception {
        //Map<String,Object> ipInfo=new HashMap<String,Object>();
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("ip", ip);
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            //System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
            String body= EntityUtils.toString(response.getEntity());
            logger.debug("body={}",body);
            JSONObject object= JSON.parseObject(body);
            int showapi_res_code=object.getInteger("showapi_res_code");
            logger.debug("showapi_res_code={}",showapi_res_code);
            JSONObject showapi_res_body=object.getJSONObject("showapi_res_body");
            logger.debug("showapi_res_body={}",showapi_res_body);
            if (showapi_res_code==0){
                return JSON.toJSONString(showapi_res_body);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new Exception();
    }
}
